package com.ruoyi.chengji.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.pingjiao.domain.CourseclassStudent;
import com.ruoyi.pingjiao.domain.vo.ExcelVo;
import com.ruoyi.pingjiao.domain.vo.StudentDto;
import com.ruoyi.pingjiao.domain.vo.StudentScore;
import com.ruoyi.pingjiao.service.ICourseclassStudentService;
import com.ruoyi.pingjiao.utils.WordUtils;

import io.jsonwebtoken.lang.Collections;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 学生上课Controller
 * 
 * @author 牛亚博
 * @date 2023-07-08
 */
@RestController
@RequestMapping("/score/CourseclassStudent")
public class CourseclassStudentController extends BaseController
{
    @Autowired
    private ICourseclassStudentService courseclassStudentService;

    /**
     * 查询学生上课列表
     */
    @PreAuthorize("@ss.hasPermi('score:courseclassStudent:list')")
    @GetMapping("/list")
    public TableDataInfo list(CourseclassStudent courseclassStudent)
    {
        startPage();
        List<CourseclassStudent> list = courseclassStudentService.selectCourseclassStudentList(courseclassStudent);
        return getDataTable(list);
    }

    /**
     * 导出学生上课列表
     */
    @PreAuthorize("@ss.hasPermi('score:courseclassStudent:export')")
    @Log(title = "学生上课", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CourseclassStudent courseclassStudent)
    {
        List<CourseclassStudent> list = courseclassStudentService.selectCourseclassStudentList(courseclassStudent);
        ExcelUtil<CourseclassStudent> util = new ExcelUtil<CourseclassStudent>(CourseclassStudent.class);
        util.exportExcel(response, list, "学生上课数据");
    }

    /**
     * 获取学生上课详细信息
     */

    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable Long studentId)
    {
        return AjaxResult.success(courseclassStudentService.selectCourseclassStudentByStudentId(studentId));
    }

    @PostMapping("/score")
    public AjaxResult getScore( StudentDto studentVo)
    {
        System.out.println(studentVo);
        return AjaxResult.success(courseclassStudentService.selectScoreByStudentId(studentVo));
    }

    /**
     * 获取学生课表信息
     * @param
     * @return
     */
    @PostMapping("course")
    public AjaxResult getCourseInfo( StudentDto studentVo){
        startPage();
        return AjaxResult.success(courseclassStudentService.selectCourseByStudentId(studentVo));
    }

    /**
     * 查询上课学期
     * @param userId
     * @return
     */
    @GetMapping("term/{userId}")
    public AjaxResult getTerm(@PathVariable Long userId){
        List<String> list = courseclassStudentService.selectTermByStudentId(userId);
//        List<Map<String,String>>list1=new ArrayList<>();
//      JSONArray arrays=new JSONArray();
//
//        for (String s:list
//             ) {
//            JSONObject jsonObject=new JSONObject();
//            jsonObject.put("name",s);
//
//            arrays.add(jsonObject);
//
//        }
//        System.out.println(arrays);
        return AjaxResult.success(list);
    }
    /**
     * 新增学生上课
     */
    @PreAuthorize("@ss.hasPermi('score:courseclassStudent:add')")
    @Log(title = "学生上课", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CourseclassStudent courseclassStudent)
    {
        return toAjax(courseclassStudentService.insertCourseclassStudent(courseclassStudent));
    }

    /**
     * 修改学生上课
     */
    @PreAuthorize("@ss.hasPermi('score:courseclassStudent:edit')")
    @Log(title = "学生上课", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CourseclassStudent courseclassStudent)
    {
        return toAjax(courseclassStudentService.updateCourseclassStudent(courseclassStudent));
    }

    /**
     * 删除学生上课
     */
    @PreAuthorize("@ss.hasPermi('score:courseclassStudent:remove')")
    @Log(title = "学生上课", businessType = BusinessType.DELETE)
	@DeleteMapping("/{studentIds}")
    public AjaxResult remove(@PathVariable Long[] studentIds)
    {
        return toAjax(courseclassStudentService.deleteCourseclassStudentByStudentIds(studentIds));
    }

    /**
     * 导出授课信息
     * @param response
     * @param courseclassId
     */
    @PreAuthorize("@ss.hasPermi('score:courseclassStudent:export')")
    @Log(title = "授课信息", businessType = BusinessType.EXPORT)
    @PostMapping("class/export/{courseclassId}")
    public void classExport(HttpServletResponse response,@PathVariable Long courseclassId){
       List<StudentScore>list=courseclassStudentService.exportScore(courseclassId);
//       ExcelUtil<StudentScore>util=new ExcelUtil<>(StudentScore.class);
//       util.exportExcel(response,list,"授课信息");
//       System.out.println(list);
        XWPFDocument document= new XWPFDocument();
        List<String> list1 = new ArrayList<>();
        list1.add("1");
        list1.add("2");
        list1.add("3");
        list1.add("41");
        try {
            // 这里写你在数据库中查出的数据
            for (StudentScore studentScore1:list){
                //添加标题
                XWPFParagraph titleParagraph = document.createParagraph();
                XWPFRun titleParagraphRun = titleParagraph.createRun();
                titleParagraphRun.setText("授课班级："+studentScore1.getMetaclassName());

                XWPFParagraph titleParagraph1 = document.createParagraph();
                XWPFRun titleParagraphRun1 = titleParagraph1.createRun();
                titleParagraphRun1.setText("授课教师："+studentScore1.getRealName());

                XWPFParagraph titleParagraph2 = document.createParagraph();
                XWPFRun titleParagraphRun2 = titleParagraph2.createRun();
                titleParagraphRun2.setText("课程名称: "+studentScore1.getCourseName());

                XWPFParagraph xwpfParagraph=document.createParagraph();
                XmlCursor cursor= xwpfParagraph.getCTP().newCursor();
                XWPFDocument xwpfDocument = xwpfParagraph.getDocument();
                XWPFTable table = xwpfDocument.insertNewTbl(cursor);

                XWPFTableRow row_0 = table.getRow(0);
                row_0.getCell(0).setText("最高分");
                row_0.addNewTableCell().setText("最低分");
                row_0.addNewTableCell().setText("平均分");
                row_0.addNewTableCell().setText("0~59");
                row_0.addNewTableCell().setText("60~69");
                row_0.addNewTableCell().setText("70~79");
                row_0.addNewTableCell().setText("80~89");
                row_0.addNewTableCell().setText("90~100");

                XWPFTableRow row_1 = table.createRow();
                row_1.getCell(0).setText(String.valueOf(studentScore1.getTopScore()));
                row_1.getCell(1).setText(String.valueOf(studentScore1.getLowScore()));
                row_1.getCell(2).setText(String.valueOf(studentScore1.getAverageScore()));
                row_1.getCell(3).setText(String.valueOf(studentScore1.getNumber1()));
                row_1.getCell(4).setText(String.valueOf(studentScore1.getNumber2()));
                row_1.getCell(5).setText(String.valueOf(studentScore1.getNumber3()));
                row_1.getCell(6).setText(String.valueOf(studentScore1.getNumber4()));
                row_1.getCell(7).setText(String.valueOf(studentScore1.getNumber5()));

                setTableLocation(table,"both");
                setCellLocation(table,"BOTH","both");
                xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));
            }
            SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
            String fileName = new String("word导出".getBytes("UTF-8"), "iso-8859-1");
            new WordUtils().exportWord(document,response,fileName+sdf.format(new Date()));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("导出成功！！！！");
    }
    /**
     * 设置单元格水平位置和垂直位置
     *
     * @param xwpfTable
     * @param verticalLoction    单元格中内容垂直上TOP，下BOTTOM，居中CENTER，BOTH两端对齐
     * @param horizontalLocation 单元格中内容水平居中center,left居左，right居右，both两端对齐
     */
    public static void setCellLocation(XWPFTable xwpfTable, String verticalLoction, String horizontalLocation) {
        List<XWPFTableRow> rows = xwpfTable.getRows();
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                CTTc cttc = cell.getCTTc();
                CTP ctp = cttc.getPList().get(0);
                CTPPr ctppr = ctp.getPPr();
                if (ctppr == null) {
                    ctppr = ctp.addNewPPr();
                }
                CTJc ctjc = ctppr.getJc();
                if (ctjc == null) {
                    ctjc = ctppr.addNewJc();
                }
                ctjc.setVal(STJc.Enum.forString(horizontalLocation)); //水平居中
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf(verticalLoction));//垂直居中
            }
        }
    }

    /**
     * 设置表格位置
     *
     * @param xwpfTable
     * @param location  整个表格居中center,left居左，right居右，both两端对齐
     */
    public static void setTableLocation(XWPFTable xwpfTable, String location) {
        xwpfTable.setWidth("100%");
        CTTbl cttbl = xwpfTable.getCTTbl();
        CTTblPr tblpr = cttbl.getTblPr() == null ? cttbl.addNewTblPr() : cttbl.getTblPr();
        CTJc cTJc = tblpr.addNewJc();
        cTJc.setVal(STJc.Enum.forString(location));

    }
    public static void main(String[]args) throws Exception {
        InputStream inputStream=new FileInputStream("C:\\Sxl\\达成度分析测试用例.xlsx");
        ExcelUtil<ExcelVo>excelVoExcelUtil=new ExcelUtil<>(ExcelVo.class);
        List<ExcelVo> 数据统计 = excelVoExcelUtil.importExcel("数据统计", inputStream, 4);
        System.out.println(数据统计);
    }
}
